#!/bin/bash

: '

生成证书
cd /opt/apps/alist
openssl req -newkey rsa:2048 -nodes -keyout example.key -x509 -days 365 -out example.crt

'

SWNAME=frp-client
SWVER=0.61.1

# 注意安装顺序，后装者依赖前装者
DEB_PATH1=./downloads/${SWNAME}.tar.gz

DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}
app_dir=/opt/apps/${SWNAME}

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

function sw_download() {
	tmpdns=`cd /exbin && droidexec ./vm_getHostByName.sh ${GITHUB_PROXY_HOST}`
	exit_if_fail $? "DNS解析失败"
	echo "$tmpdns" >> /etc/hosts

	case "${CURRENT_VM_ARCH}" in
		"arm64")
			# https://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/pool/universe/k/kdenlive/
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/fatedier/frp/releases/download/v0.61.1/frp_0.61.1_linux_arm64.tar.gz"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		*) exit_unsupport ;;
	esac
}

function sw_install() {

	# sudo apt-get install -y socat
	# exit_if_fail $? "依赖库 socat 安装失败"

	mkdir -p ${app_dir}

	echo "正在解压. . ."
	tar -xzf ${DEB_PATH1} --overwrite -C ${app_dir}/..
	exit_if_fail $? "安装失败，软件包：${DEB_PATH1}"

	rm -rf ${app_dir}
	mv -f /opt/apps/frp_${SWVER}_linux_arm64  ${app_dir}/
	exit_if_fail $? "文件夹重命名失败"

	# # s 权限, 表示运行这个程序时需要有root权限
	# chmod +s ${app_dir}/x-ui
	# exit_if_fail $? "s权限添加失败"

	# 客户端不需要这些文件
	rm -rf ${app_dir}/frps*
}

function sw_create_desktop_file() {

	echo "正在生成启动程序"
	tmpfile=/usr/bin/${SWNAME}
	cat <<- EOF > ${tmpfile}
		#!/bin/bash
		${app_dir}/frpc -c ${app_dir}/frpc.toml
	EOF
	chmod 755 ${tmpfile}

	echo "正在生成桌面文件"
	cat <<- EOF > ${DSK_PATH}
		[Desktop Entry]
		Name=frp客户端
		Exec=${SWNAME}
		Path=${app_dir}
		Terminal=true
		Type=Application
	EOF
	cp2desktop ${DSK_PATH}

	cat <<- EOF > ${DIR_DESKTOP_FILES}/${SWNAME}-cfg.desktop
		[Desktop Entry]
		Name=配置frp
		Exec=notepad ${app_dir}/frpc.toml
		Type=Application
	EOF
	cp2desktop ${DIR_DESKTOP_FILES}/${SWNAME}-cfg.desktop

	gxmessage -title "提示"     $'\n安装完成\n\n'  -center
}

if [ "${action}" == "卸载" ]; then
	# echo "暂不支持卸载"
	# exit 1
	rm -rf /usr/bin/${SWNAME}
	rm -rf ${DEB_PATH1} ${app_dir}
	rm2desktop ${DSK_FILE}
	rm2desktop ${SWNAME}-cfg.desktop
	apt-get clean
else
	sw_download
	sw_install
	sw_create_desktop_file
fi

